class FetionMessage < ActiveRecord::Base
  belongs_to :fetion
  
  def self.count_by_fetion_id_and_status(fetion_id, status)
    count( :conditions => [
      'fetion_id = ? and status = ?',
      fetion_id,
      status
    ])
  end
  
  def user
    User.find_by_mobile(mobile) || User.find_by_fetion_user_id(fetion_user_id) || User.find_by_fetion_sid(fetion_sid)
  end
  
  def before_create
    self.recieved_at = Time.now
    do_it_even_exception do 
      user.bind_if_present!(
        :fetion_sid => fetion_sid,
        :fetion_user_id => fetion_user_id
      ) if user.present?      
    end
  end
  
  def do_it_even_exception
    begin
      yield
    rescue
      logger.error "#{$!}:#{$@}"
      puts "#{$!}:#{$@}"      
    end
  end
end
